package com.xxxx.yebserver.config.socket;

import com.xxxx.yebserver.common.utils.JwtTokenUtils;
import com.xxxx.yebserver.config.security.JwtAuthenticationTokenFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.List;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Autowired
    UserDetailsService userDetailsService;

    /**
     * 添加这个Endpoint,这样在网页可以通过websocket连接上服务
     * 配置websocket地址，并且可以指定前端是否使用sockjs
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //将ws/ep注册为stomp端点，用户连接了这个端点就可以进行websocket通讯
        registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
    }


    /**
     * 输入通道参数配置（因为使用jwt令牌认证，所以需要配置）
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                //判断是否是连接,如果是需要获取token令牌，并设置到用户对象
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if(accessor == null) return message;
                StompCommand command = accessor.getCommand();
                //判断是否是首次连接
                if(StompCommand.CONNECT.equals(command)){
                    String token = accessor.getFirstNativeHeader("token");
                    if(!StringUtils.isEmpty(token) && jwtTokenUtils.validateToken(token)){
                        String username = jwtTokenUtils.getUserFromToken(token);
                        if(!StringUtils.isEmpty(username)){
                            //登录并设置到用户对象
                            UserDetails userDetail = userDetailsService.loadUserByUsername(username);
                            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
                            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                            accessor.setUser(authenticationToken);
                        }
                    }
                }
                return message;
            }
        });
    }

    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //配置代理域，可以配置多个，配置代理目的地前缀为/queue,可以在配置域上向客户端推送消息
        registry.enableSimpleBroker("/queue");
        // 点对点使用的订阅前缀（客户端订阅路径上会体现出来），不设置的话，默认也是/user/
        registry.setUserDestinationPrefix("/user/");
    }

    @Bean
    public HttpSessionHandshakeInterceptor httpSessionHandshakeInterceptor(){
        return new HttpSessionHandshakeInterceptor();
    }
}
